import asyncio

import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from src.database import Base

# 测试数据库 URL
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

# 创建测试数据库引擎
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False, future=True)

# 创建测试会话工厂
TestAsyncSessionLocal = async_sessionmaker(
    bind=test_engine, class_=AsyncSession, expire_on_commit=False, autoflush=False
)


async def override_get_db():
    """覆盖数据库依赖,使用测试数据库"""
    async with TestAsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()


@pytest.fixture(scope="session")
def event_loop():
    """创建事件循环"""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="session", autouse=True)
def setup_test_database(event_loop):
    """设置测试数据库 - session级别,只创建一次"""

    # 创建表
    async def create_tables():
        async with test_engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)

    # 删除表
    async def drop_tables():
        async with test_engine.begin() as conn:
            await conn.run_sync(Base.metadata.drop_all)

    # 创建表
    event_loop.run_until_complete(create_tables())

    yield

    # 删除表
    event_loop.run_until_complete(drop_tables())


@pytest_asyncio.fixture(scope="function", autouse=True)
async def clean_data():
    async with TestAsyncSessionLocal() as session:
        # 清理所有表数据
        for table in reversed(Base.metadata.sorted_tables):
            await session.execute(table.delete())
        await session.commit()
        yield
        await session.close()
